//
//  COSquareDetailViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/22.
//

import UIKit
import MJRefresh

class COSquareDetailViewController: COBaseViewController {
    var model: COHomeListModel = COHomeListModel() {
        didSet {
            imageView.kf.setImage(with: URL(string: model.photo))
            likeButton.isSelected = model.like

        }
    }
    
    var remarks: [COQARemarkModel] = []
    var contents: [COBaseCellModel] = []
    
    var page = 1
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        configCell()
        
        self.getDetail()
        self.getData()
        NotificationCenter.default.addObserver(self, selector: #selector(followChange), name: NSNotification.Name(rawValue: "FolloSuccess"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func configUI() {
        self.navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: tipButton)
        title = "Details"
        view.backgroundColor = .rgba(17, 7, 41, 1)
        view.addSubview(tableView)
        view.addSubview(lineView)
        view.addSubview(answerTextField)
        view.addSubview(flowButton)
        view.addSubview(likeButton)
        
        tableView.tableHeaderView = imageView
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(navHeight + statusBarHeight)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(lineView.snp.top)
        }
        
        answerTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().offset(-bottomSafeHeight)
            make.height.equalTo(40)
            make.right.equalTo(flowButton.snp.left).offset(-20)
        }
        
        likeButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(answerTextField)
        }
        
        flowButton.snp.makeConstraints { make in
            make.right.equalTo(likeButton.snp.left).offset(-20)
            make.centerY.equalTo(answerTextField)
        }
        
        
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(answerTextField.snp.top).offset(-10)
            make.height.equalTo(1)
        }
    }
    
    func configCell() {
        contents = []
        let model = COQADetailHeaderModel()
        model.id = self.model.userId
        model.avatar = self.model.sculpture
        model.name = self.model.nickName
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM d, YYYY"
        model.time = formatter.string(from: self.model.createDate)
        model.showID = !self.model.level.isEmpty
        model.isFollow = self.model.follow
        model.tag = self.model.type.tag
        model.content = self.model.content
        model.showButton = true
        model.likeNum = self.model.likes
        model.flowNum = self.model.gifts
        model.like = self.model.like
        contents.append(model)
        
        for item in remarks {
            let model = COQADetailAnswerModel()
            model.avatar = item.sculpture
            model.name = item.nickName
            let formatter = DateFormatter()
            formatter.dateFormat = "MMMM d, YYYY"
            model.time = formatter.string(from: item.createDate)
            model.content = item.comment
            contents.append(model)
        }
        
        tableView.reloadData()
    }
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .rgba(17, 7, 41, 1)
        tableV.delegate = self
        tableV.dataSource = self
        tableV.register(cellWithClass: CODetailHomeTableViewCell.self)
        tableV.register(cellWithClass: CODetailAnswerTableViewCell.self)
        tableV.separatorStyle = .none
        
        tableV.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [weak self] in
            self?.page = 1
            self?.getData()
        })
        
        tableV.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            [weak self] in
            self?.page += 1
            self?.getData()
        })
        return tableV
    }()
    
    private lazy var imageView: UIImageView = {
        let imgV = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREENWIDTH, height: 385))
        return imgV
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .white.withAlphaComponent(0.15)
        return view
    }()
    
    private lazy var answerTextField: UITextField = {
        let tf = UITextField()
        tf.backgroundColor = .rgba(41, 32, 63, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 20
        
        tf.font = .medium(15)
        tf.textColor = .white
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("Comment")?.font(.medium(15)).textColor(.white)
        })
        tf.textAlignment = .center
        tf.returnKeyType = .done
        tf.delegate = self
        return tf
    }()
    
    private lazy var flowButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "位图备份 2"), for: .normal)
        btn.addTarget(self, action: #selector(flow), for: .touchUpInside)
        return btn
    }()
    
    private lazy var likeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 6(1)"), for: .normal)
        btn.setImage(UIImage(named: "编组 19"), for: .selected)
        btn.addTarget(self, action: #selector(like), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tipButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 23"), for: .normal)
        btn.addTarget(self, action: #selector(showTip), for: .touchUpInside)
        return btn
    }()
}

extension COSquareDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = contents[indexPath.row]
        return model.cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let model = contents[indexPath.row] as? COQADetailHeaderModel {
            let cell = tableView.dequeueReusableCell(withClass: CODetailHomeTableViewCell.self)
            cell.clickAction = {[weak self] in
                guard let self = self else {
                    return
                }
                self.follo(self.model.userId, isFollo: !self.model.follow)
            }
            cell.flowAction = {[weak self] in
                let vc = COGiftViewController()
                vc.id = self?.model.id ?? 0
                vc.okAction = {[weak vc] in
                    vc?.dismiss(animated: true)
                    self?.getDetail()
                }
                self?.present(vc, animated: true)
            }
            cell.model = model
            cell.likeAction = {[weak self] in
                self?.like()
            }
            
            cell.headerAction = {[weak self] in
                guard let self = self else { return }
                let vc = COHeViewController(id: self.model.userId)
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return cell
        }
        
        if let model = contents[indexPath.row] as? COQADetailAnswerModel {
            let cell = tableView.dequeueReusableCell(withClass: CODetailAnswerTableViewCell.self)
            cell.model = model
            return cell
        }
        
        return UITableViewCell()
    }
    
    private func getDetail() {
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: homeProvider, target: .sqDetail(id: model.id)) { text in
            self.view.hideToastActivity()
            guard let model = COHomeListModel.deserialize(from: text.dic) else {
                return
            }
            self.model = model
            
            self.configCell()
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
    
    private func getData() {
        CONetwork.sendRequest(provider: homeProvider, target: .sqRemark(page: page, id: model.id)) { text in
            guard let array = text.array else {
                return
            }
            
            let arr = array.map { dic in
                let model = COQARemarkModel.deserialize(from: dic)!
                return model
            }
            
            if self.page == 1 {
                self.remarks = arr
                self.tableView.mj_header?.endRefreshing()
            } else {
                self.remarks.append(contentsOf: arr)
            }
            
            if arr.count < 20 {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.configCell()
        } failedBlock: { _, text in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.makeToast(text, position: .center)
        }

    }
    
    private func send() {
        guard let text = answerTextField.text, !text.isEmpty else {
            return
        }
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: homeProvider, target: .sqAnswer(id: model.id, comment: text)) { _ in
            self.view.hideToastActivity()
            self.tableView.mj_header?.beginRefreshing()
            self.answerTextField.text = ""
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
    
    @objc
    private func like() {
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: homeProvider, target: model.like ? .sqUnlike(id: model.id) : .sqLike(id: model.id)) { _ in
            self.view.hideToastActivity()
            self.model.like = !self.model.like
            if self.model.like {
                self.model.likes += 1
            } else {
                self.model.likes -= 1
            }
            self.likeButton.isSelected = self.model.like
            self.configCell()
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
    
    @objc
    private func flow() {
        let vc = COGiftViewController()
        vc.id = model.id
        vc.okAction = {[weak self, weak vc] in
            vc?.dismiss(animated: true)
            self?.getDetail()
        }
        self.present(vc, animated: true)
    }
//    private func getData() {
//        self.view.makeToastActivity(.center)
//        CONetwork.sendRequest(provider: homeProvider, target: .qaDetail(id: qaId)) { text in
//            self.view.hideToastActivity()
//            guard let array = text.array else {
//                return
//            }
//
//            self.contents = array.map({ dic in
//                let model = COHomeFoodListModel.deserialize(from: dic)!
//                return model
//            })
//            self.tableView.reloadData()
//        } failedBlock: { _, text in
//            self.view.hideToastActivity()
//            self.view.makeToast(text, position: .center)
//        }
//
//    }
}

extension COSquareDetailViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.send()
        textField.resignFirstResponder()
        return true
    }
    
    @objc
    private func followChange() {
        self.getDetail()
    }
}
